package com.cloud.flowable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.exception.CustomException;
import com.cloud.flowable.entity.WfCategory;
import com.cloud.flowable.mapper.WfCategoryMapper;
import com.cloud.flowable.service.IWfCategoryService;
import com.cloud.utils.ExcelPoiUtils;
import com.cloud.utils.ServletUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 流程分类业务层处理
 */
@Service
public class WfCategoryServiceImpl implements IWfCategoryService {

    @Resource
    private WfCategoryMapper categoryMapper;

    /**
     * 流程分类分页
     */
    @Override
    public List<WfCategory> getCategoryList(WfCategory category) {
        return categoryMapper.getCategoryList(category);
    }

    /**
     * 流程分类详情
     */
    @Override
    public WfCategory queryById(Long categoryId) {
        return categoryMapper.selectById(categoryId);
    }

    /**
     * 流程分类新增
     */
    @Override
    public int saveCategory(WfCategory wfCategory) {
        if (checkCategoryCodeUnique(wfCategory)) {
            throw new CustomException("流程编码不可重复,该流程编码已经存在");
        }
        return categoryMapper.insert(wfCategory);
    }

    /**
     * 流程分类修改
     */
    @Override
    public int updateCategory(WfCategory wfCategory) {
        if (checkCategoryCodeUnique(wfCategory)) {
            throw new CustomException("流程编码不可重复,该流程编码已经存在");
        }
        return categoryMapper.updateById(wfCategory);
    }

    /**
     * 流程分类删除
     */
    @Override
    public int removeIds(List<Long> ids) {
        return categoryMapper.deleteBatchIds(ids);
    }


    /**
     * 流程分类导出
     */
    @Override
    public void export(WfCategory wfCategory) {
        List<WfCategory> wfCategories = categoryMapper.getCategoryList(wfCategory);
        String titleName = "流程分类";
        ExcelPoiUtils.exportExcel(wfCategories, titleName, titleName,
                WfCategory.class, titleName + ".xls", ServletUtils.getResponse());
    }

    /**
     * 校验流程编码是否唯一
     */
    public boolean checkCategoryCodeUnique(WfCategory wfCategory) {
        QueryWrapper<WfCategory> wfCategoryQueryWrapper = new QueryWrapper<>();
        wfCategoryQueryWrapper.eq("code", wfCategory.getCode())
                .ne(Objects.nonNull(wfCategory.getCategoryId()),
                        "category_id", wfCategory.getCategoryId());
        return categoryMapper.exists(wfCategoryQueryWrapper);
    }

}
